<template>
  <div class="idcard-verification-page">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-content">
        <button class="back-btn" @click="goBack">
          <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <path d="M724 218.3V141c0-6.7-7.7-10.4-12.9-6.3L260.3 486.8a31.86 31.86 0 0 0 0 50.3l450.8 352.1c5.3 4.1 12.9.4 12.9-6.3v-77.3c0-4.9-2.3-9.6-6.1-12.6l-360-281 360-281.1c3.8-3 6.1-7.7 6.1-12.6z" fill="currentColor"/>
          </svg>
          返回
        </button>
      </div>
    </header>

    <!-- 主体内容 -->
    <div class="main-content">
      <div class="container">
        <!-- 标题区域 -->
        <div class="page-header">
          <div class="title-icon">🪪</div>
          <h1 class="page-title">实名认证</h1>
          <p class="page-subtitle">上传您的身份证进行实名认证，保障账号安全</p>
        </div>

        <!-- 上传区域 -->
        <div class="upload-section">
          <div class="upload-container">
            <!-- 身份证正面上传 -->
            <div class="upload-card">
              <div class="card-header">
                <span class="card-title">身份证正面</span>
                <span class="required-badge">必填</span>
              </div>
              <div 
                class="upload-area"
                :class="{ 'has-image': frontPreview, 'drag-over': frontDragOver }"
                @click="triggerFrontUpload"
                @drop.prevent="handleFrontDrop"
                @dragover.prevent="frontDragOver = true"
                @dragleave.prevent="frontDragOver = false"
              >
                <input
                  ref="frontInput"
                  type="file"
                  accept="image/jpeg,image/jpg,image/png"
                  @change="handleFrontChange"
                  style="display: none"
                />
                
                <div v-if="!frontPreview" class="upload-placeholder">
                  <div class="upload-icon">
                    <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                      <path d="M864 248H728l-32.4-90.8a32.07 32.07 0 0 0-30.2-21.2H358.6c-13.5 0-25.6 8.5-30.1 21.2L296 248H160c-44.2 0-80 35.8-80 80v456c0 44.2 35.8 80 80 80h704c44.2 0 80-35.8 80-80V328c0-44.2-35.8-80-80-80zM512 716c-88.4 0-160-71.6-160-160s71.6-160 160-160 160 71.6 160 160-71.6 160-160 160z" fill="currentColor"/>
                    </svg>
                  </div>
                  <p class="upload-text">点击或拖拽上传</p>
                  <p class="upload-hint">支持 JPG、PNG 格式，大小不超过 5MB</p>
                </div>

                <div v-else class="image-preview">
                  <img :src="frontPreview" alt="身份证正面" />
                  <div class="image-overlay">
                    <button class="overlay-btn" @click.stop="removeFrontImage">
                      <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                        <path d="M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z" fill="currentColor"/>
                      </svg>
                      删除
                    </button>
                  </div>
                </div>
              </div>
              <div v-if="frontFile" class="file-info">
                <span class="file-name">{{ frontFile.name }}</span>
                <span class="file-size">{{ formatFileSize(frontFile.size) }}</span>
              </div>
            </div>

            <!-- 身份证背面上传 -->
            <div class="upload-card">
              <div class="card-header">
                <span class="card-title">身份证背面</span>
                <span class="required-badge">必填</span>
              </div>
              <div 
                class="upload-area"
                :class="{ 'has-image': backPreview, 'drag-over': backDragOver }"
                @click="triggerBackUpload"
                @drop.prevent="handleBackDrop"
                @dragover.prevent="backDragOver = true"
                @dragleave.prevent="backDragOver = false"
              >
                <input
                  ref="backInput"
                  type="file"
                  accept="image/jpeg,image/jpg,image/png"
                  @change="handleBackChange"
                  style="display: none"
                />
                
                <div v-if="!backPreview" class="upload-placeholder">
                  <div class="upload-icon">
                    <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                      <path d="M864 248H728l-32.4-90.8a32.07 32.07 0 0 0-30.2-21.2H358.6c-13.5 0-25.6 8.5-30.1 21.2L296 248H160c-44.2 0-80 35.8-80 80v456c0 44.2 35.8 80 80 80h704c44.2 0 80-35.8 80-80V328c0-44.2-35.8-80-80-80zM512 716c-88.4 0-160-71.6-160-160s71.6-160 160-160 160 71.6 160 160-71.6 160-160 160z" fill="currentColor"/>
                    </svg>
                  </div>
                  <p class="upload-text">点击或拖拽上传</p>
                  <p class="upload-hint">支持 JPG、PNG 格式，大小不超过 5MB</p>
                </div>

                <div v-else class="image-preview">
                  <img :src="backPreview" alt="身份证背面" />
                  <div class="image-overlay">
                    <button class="overlay-btn" @click.stop="removeBackImage">
                      <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                        <path d="M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z" fill="currentColor"/>
                      </svg>
                      删除
                    </button>
                  </div>
                </div>
              </div>
              <div v-if="backFile" class="file-info">
                <span class="file-name">{{ backFile.name }}</span>
                <span class="file-size">{{ formatFileSize(backFile.size) }}</span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <button 
              class="submit-btn"
              :class="{ 'disabled': !canSubmit || loading }"
              :disabled="!canSubmit || loading"
              @click="handleSubmit"
            >
              <span v-if="loading" class="loading-spinner"></span>
              <span v-else>{{ uploadStep === 'none' ? '上传并识别' : '重新识别' }}</span>
            </button>
          </div>
        </div>

        <!-- 识别结果展示 -->
        <transition name="fade">
          <div v-if="ocrResult" class="result-section">
            <div class="result-header">
              <div class="result-icon success">✅</div>
              <h2 class="result-title">识别成功</h2>
              <p class="result-subtitle">请仔细核对以下信息</p>
            </div>

            <div class="result-content">
              <!-- 正面信息 -->
              <div class="info-card">
                <h3 class="info-card-title">基本信息</h3>
                <div class="info-grid">
                  <div class="info-item">
                    <span class="info-label">姓名</span>
                    <span class="info-value">{{ ocrResult.front?.姓名?.words || '-' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">性别</span>
                    <span class="info-value">{{ ocrResult.front?.性别?.words || '-' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">民族</span>
                    <span class="info-value">{{ ocrResult.front?.民族?.words || '-' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">出生日期</span>
                    <span class="info-value">{{ ocrResult.front?.出生?.words || '-' }}</span>
                  </div>
                  <div class="info-item full-width">
                    <span class="info-label">身份证号</span>
                    <span class="info-value highlight">{{ ocrResult.front?.公民身份号码?.words || '-' }}</span>
                  </div>
                  <div class="info-item full-width">
                    <span class="info-label">住址</span>
                    <span class="info-value">{{ ocrResult.front?.住址?.words || '-' }}</span>
                  </div>
                </div>
              </div>

              <!-- 背面信息 -->
              <div class="info-card">
                <h3 class="info-card-title">证件信息</h3>
                <div class="info-grid">
                  <div class="info-item">
                    <span class="info-label">签发机关</span>
                    <span class="info-value">{{ ocrResult.back?.签发机关?.words || '-' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">有效期限</span>
                    <span class="info-value">{{ ocrResult.back?.签发日期?.words || '-' }} 至 {{ ocrResult.back?.失效日期?.words || '-' }}</span>
                  </div>
                </div>
              </div>
              

              <!-- 确认按钮 -->
              <div class="confirm-actions">
                <button class="confirm-btn" @click="handleConfirm">
                  <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                    <path d="M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 0 0-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z" fill="currentColor"/>
                  </svg>
                  确认信息无误
                </button>
              </div>
            </div>
          </div>
        </transition>
      </div>
    </div>

    <!-- Toast 提示 -->
    <transition name="toast">
      <div v-if="toast.show" class="toast" :class="toast.type">
        <span class="toast-icon">
          <svg v-if="toast.type === 'success'" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 0 1-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z" fill="currentColor"/>
          </svg>
          <svg v-else viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm165.4 618.2l-66-0.3L512 563.4l-99.3 118.4-66.1 0.3c-4.4 0-8-3.5-8-8 0-1.9 0.7-3.7 1.9-5.2l130.1-155L340.5 359a8.32 8.32 0 0 1-1.9-5.2c0-4.4 3.6-8 8-8l66.1 0.3L512 464.6l99.3-118.4 66-0.3c4.4 0 8 3.5 8 8 0 1.9-0.7 3.7-1.9 5.2L553.5 514l130 155c1.2 1.5 1.9 3.3 1.9 5.2 0 4.4-3.6 8-8 8z" fill="currentColor"/>
          </svg>
        </span>
        <span class="toast-message">{{ toast.message }}</span>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../stores/user'
import { uploadIdCard, ocrIdCard, submitIdCardVerification } from '../../api/auth'

const router = useRouter()
const userStore = useUserStore()

// 文件和预览
const frontFile = ref(null)
const backFile = ref(null)
const frontPreview = ref('')
const backPreview = ref('')
const frontInput = ref(null)
const backInput = ref(null)

// 拖拽状态
const frontDragOver = ref(false)
const backDragOver = ref(false)

// 上传状态
const loading = ref(false)
const uploadStep = ref('none') // none, uploading, uploaded, recognizing, completed
const uploadedUrls = ref({
  front: '',
  back: ''
})

// OCR 识别结果
const ocrResult = ref(null)

// Toast 提示
const toast = ref({
  show: false,
  message: '',
  type: 'success'
})

// 文件大小限制 (5MB)
const MAX_FILE_SIZE = 5 * 1024 * 1024

// 是否可以提交
const canSubmit = computed(() => {
  return frontFile.value && backFile.value && !loading.value
})

// 显示 Toast
const showToast = (message, type = 'success') => {
  toast.value = {
    show: true,
    message,
    type
  }
  setTimeout(() => {
    toast.value.show = false
  }, 3000)
}

// 验证文件
const validateFile = (file) => {
  if (!file) {
    showToast('请选择文件', 'error')
    return false
  }

  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png']
  if (!allowedTypes.includes(file.type)) {
    showToast('仅支持 JPG、PNG 格式的图片', 'error')
    return false
  }

  // 验证文件大小
  if (file.size > MAX_FILE_SIZE) {
    showToast('文件大小不能超过 5MB', 'error')
    return false
  }

  return true
}

// 创建预览
const createPreview = (file) => {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.onload = (e) => resolve(e.target.result)
    reader.readAsDataURL(file)
  })
}

// 添加马赛克效果（优化版，效果更明显）
const applyMosaic = (imageUrl, regions) => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.crossOrigin = 'anonymous'
    img.onload = () => {
      try {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d', { willReadFrequently: true })
        
        canvas.width = img.width
        canvas.height = img.height
        
        // 绘制原始图片
        ctx.drawImage(img, 0, 0)
        
        console.log('🎨 开始应用马赛克，图片尺寸:', img.width, 'x', img.height)
        console.log('🎨 遮挡区域数量:', regions.length)
        
        // 对指定区域添加马赛克
        regions.forEach((region, index) => {
          const { x, y, width, height } = region
          const mosaicSize = 30 // 更大的马赛克块，效果更明显
          
          console.log(`🎨 区域 ${index + 1}: x=${x}, y=${y}, w=${width}, h=${height}`)
          
          // 获取区域图像数据
          const imageData = ctx.getImageData(x, y, width, height)
          
          // 应用马赛克效果
          for (let row = 0; row < height; row += mosaicSize) {
            for (let col = 0; col < width; col += mosaicSize) {
              // 计算当前块的平均颜色
              const blockWidth = Math.min(mosaicSize, width - col)
              const blockHeight = Math.min(mosaicSize, height - row)
              
              let r = 0, g = 0, b = 0, count = 0
              
              for (let y2 = 0; y2 < blockHeight; y2++) {
                for (let x2 = 0; x2 < blockWidth; x2++) {
                  const idx = ((row + y2) * width + (col + x2)) * 4
                  r += imageData.data[idx]
                  g += imageData.data[idx + 1]
                  b += imageData.data[idx + 2]
                  count++
                }
              }
              
              r = Math.floor(r / count)
              g = Math.floor(g / count)
              b = Math.floor(b / count)
              
              // 填充马赛克块
              for (let y2 = 0; y2 < blockHeight; y2++) {
                for (let x2 = 0; x2 < blockWidth; x2++) {
                  const idx = ((row + y2) * width + (col + x2)) * 4
                  imageData.data[idx] = r
                  imageData.data[idx + 1] = g
                  imageData.data[idx + 2] = b
                }
              }
            }
          }
          
          // 将处理后的数据放回画布
          ctx.putImageData(imageData, x, y)
          
          // 二次马赛克处理增强效果（使用更大的块）
          const imageData2 = ctx.getImageData(x, y, width, height)
          const mosaicSize2 = 40 // 第二次使用更大的块
          
          for (let row = 0; row < height; row += mosaicSize2) {
            for (let col = 0; col < width; col += mosaicSize2) {
              const blockWidth = Math.min(mosaicSize2, width - col)
              const blockHeight = Math.min(mosaicSize2, height - row)
              
              let r = 0, g = 0, b = 0, count = 0
              
              for (let y2 = 0; y2 < blockHeight; y2++) {
                for (let x2 = 0; x2 < blockWidth; x2++) {
                  const idx = ((row + y2) * width + (col + x2)) * 4
                  r += imageData2.data[idx]
                  g += imageData2.data[idx + 1]
                  b += imageData2.data[idx + 2]
                  count++
                }
              }
              
              r = Math.floor(r / count)
              g = Math.floor(g / count)
              b = Math.floor(b / count)
              
              // 填充更大的马赛克块
              ctx.fillStyle = `rgb(${r}, ${g}, ${b})`
              ctx.fillRect(x + col, y + row, blockWidth, blockHeight)
            }
          }
        })
        
        console.log('✅ 马赛克处理完成')
        
        // 转换为Data URL
        resolve(canvas.toDataURL('image/jpeg', 0.9))
      } catch (error) {
        console.error('❌ 马赛克处理失败', error)
        // 如果处理失败，返回原图
        resolve(imageUrl)
      }
    }
    img.onerror = () => {
      console.error('❌ 图片加载失败')
      resolve(imageUrl)
    }
    img.src = imageUrl
  })
}

// 为身份证正面添加马赛克（遮挡姓名和身份证号）
const applyFrontMosaic = async (imageUrl) => {
  // 身份证正面敏感区域（基于标准身份证尺寸比例）
  const img = new Image()
  await new Promise(resolve => {
    img.onload = resolve
    img.src = imageUrl
  })
  
  const width = img.width
  const height = img.height
  
  console.log('📏 身份证正面尺寸:', width, 'x', height)
  
  // 计算敏感区域（扩大遮挡范围，确保完全覆盖）
  const regions = [
    // 姓名区域（右侧，上方） 扩大范围
    { 
      x: Math.floor(width * 0.2), 
      y: Math.floor(height * 0.12), 
      width: Math.floor(width * 0.45), 
      height: Math.floor(height * 0.15) 
    },
    // 性别、民族、出生区域（右侧中间） 新增
    { 
      x: Math.floor(width * 0.2), 
      y: Math.floor(height * 0.28), 
      width: Math.floor(width * 0.45), 
      height: Math.floor(height * 0.18) 
    },
    // 地址区域（右侧中下方） 新增
    { 
      x: Math.floor(width * 0.2), 
      y: Math.floor(height * 0.48), 
      width: Math.floor(width * 0.55), 
      height: Math.floor(height * 0.2) 
    },
    // 身份证号区域（底部）- 扩大范围
    { 
      x: Math.floor(width * 0.2), 
      y: Math.floor(height * 0.72), 
      width: Math.floor(width * 0.65), 
      height: Math.floor(height * 0.15) 
    }
  ]
  
  return applyMosaic(imageUrl, regions)
}

// 为身份证背面添加马赛克（遮挡有效期等）
const applyBackMosaic = async (imageUrl) => {
  const img = new Image()
  await new Promise(resolve => {
    img.onload = resolve
    img.src = imageUrl
  })
  
  const width = img.width
  const height = img.height
  
  console.log('📏 身份证背面尺寸:', width, 'x', height)
  
  // 背面敏感区域：签发机关和有效期
  const regions = [
    // 签发机关区域（底部左侧）- 扩大范围
    { 
      x: Math.floor(width * 0.15), 
      y: Math.floor(height * 0.65), 
      width: Math.floor(width * 0.5), 
      height: Math.floor(height * 0.12) 
    },
    // 有效期区域（底部中间） 扩大范围
    { 
      x: Math.floor(width * 0.25), 
      y: Math.floor(height * 0.78), 
      width: Math.floor(width * 0.5), 
      height: Math.floor(height * 0.15) 
    }
  ]
  
  return applyMosaic(imageUrl, regions)
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

// 触发文件选择
const triggerFrontUpload = () => {
  frontInput.value?.click()
}

const triggerBackUpload = () => {
  backInput.value?.click()
}

// 处理正面文件选择
const handleFrontChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (!validateFile(file)) {
    event.target.value = ''
    return
  }

  frontFile.value = file
  const originalPreview = await createPreview(file)
  // 应用马赛克效果保护隐私
  console.log('🔄 开始处理正面照片马赛克...')
  try {
    frontPreview.value = await applyFrontMosaic(originalPreview)
    showToast('已对敏感信息添加遮罩', 'success')
  } catch (error) {
    console.error('【警告】马赛克处理失败，使用原图:', error)
    frontPreview.value = originalPreview
  }
}

// 处理背面文件选择
const handleBackChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (!validateFile(file)) {
    event.target.value = ''
    return
  }

  backFile.value = file
  const originalPreview = await createPreview(file)
  // 应用马赛克效果保护隐私
  console.log('🔄 开始处理背面照片马赛克...')
  try {
    backPreview.value = await applyBackMosaic(originalPreview)
    showToast('已对敏感信息添加遮罩', 'success')
  } catch (error) {
    console.error('【警告】马赛克处理失败，使用原图:', error)
    backPreview.value = originalPreview
  }
}

// 处理正面拖拽
const handleFrontDrop = async (event) => {
  frontDragOver.value = false
  const file = event.dataTransfer.files[0]
  if (!file) return

  if (!validateFile(file)) return

  frontFile.value = file
  const originalPreview = await createPreview(file)
  // 应用马赛克效果保护隐私
  console.log('🔄 开始处理正面照片马赛克...')
  try {
    frontPreview.value = await applyFrontMosaic(originalPreview)
    showToast('已对敏感信息添加遮罩', 'success')
  } catch (error) {
    console.error('【警告】马赛克处理失败，使用原图:', error)
    frontPreview.value = originalPreview
  }
}

// 处理背面拖拽
const handleBackDrop = async (event) => {
  backDragOver.value = false
  const file = event.dataTransfer.files[0]
  if (!file) return

  if (!validateFile(file)) return

  backFile.value = file
  const originalPreview = await createPreview(file)
  // 应用马赛克效果保护隐私
  console.log('🔄 开始处理背面照片马赛克...')
  try {
    backPreview.value = await applyBackMosaic(originalPreview)
    showToast('已对敏感信息添加遮罩', 'success')
  } catch (error) {
    console.error('【警告】马赛克处理失败，使用原图:', error)
    backPreview.value = originalPreview
  }
}

// 删除正面照片
const removeFrontImage = () => {
  frontFile.value = null
  frontPreview.value = ''
  if (frontInput.value) {
    frontInput.value.value = ''
  }
}

// 删除背面照片
const removeBackImage = () => {
  backFile.value = null
  backPreview.value = ''
  if (backInput.value) {
    backInput.value.value = ''
  }
}

// 提交处理
const handleSubmit = async () => {
  if (!canSubmit.value) return

  loading.value = true

  try {
    // 步骤1: 上传到七牛云（临时禁用 - 仅使用本地预览）
    console.log('📤 正在上传身份证照片到七牛云...')
    uploadStep.value = 'uploading'
    const uploadResponse = await uploadIdCard(frontFile.value, backFile.value)
    if (!uploadResponse.success) {
      throw new Error(uploadResponse.error || '上传失败')
    }
    uploadedUrls.value = {
      front: uploadResponse.front_url,
      back: uploadResponse.back_url
    }
    console.log('✅ 照片上传成功')
    uploadStep.value = 'uploaded'
    showToast('照片上传成功，正在识别...', 'success')

    // 直接进行 OCR 识别（使用本地预览显示照片）
    console.log('🔍 正在进行 OCR 识别...')
    uploadStep.value = 'recognizing'
    
    const ocrResponse = await ocrIdCard(frontFile.value, backFile.value)
    
    if (!ocrResponse.success) {
      throw new Error(ocrResponse.error || 'OCR 识别失败')
    }

    ocrResult.value = ocrResponse.data
    uploadStep.value = 'completed'
    
    console.log('✅ OCR 识别成功:', ocrResult.value)
    showToast('身份证信息识别成功！', 'success')

    // 滚动到结果区域
    setTimeout(() => {
      document.querySelector('.result-section')?.scrollIntoView({ 
        behavior: 'smooth', 
        block: 'start' 
      })
    }, 300)

  } catch (error) {
    console.error('❌ 处理失败:', error)
    showToast(error.message || '处理失败，请重试', 'error')
    uploadStep.value = 'none'
  } finally {
    loading.value = false
  }
}

// 确认信息
const handleConfirm = async () => {
  loading.value = true
  
  try {
    // 提取身份证信息
    const name = ocrResult.value.front?.姓名?.words || ''
    const idNumber = ocrResult.value.front?.公民身份号码?.words || ''
    
    console.log('📤 提交实名认证信息...')
    console.log('  姓名:', name)
    console.log('  身份证号:', idNumber)
    
    // 调用后端API保存认证信息
    const response = await submitIdCardVerification({
      name: name,
      id_number: idNumber,
      front_data: ocrResult.value.front,
      back_data: ocrResult.value.back
    })
    
    if (response.success) {
      // 更新本地用户状态
      if (userStore.user) {
        userStore.user.is_realname_authenticated = true
        // 更新localStorage
        localStorage.setItem('user', JSON.stringify(userStore.user))
      }
      
      console.log('✅ 实名认证提交成功')
      showToast('实名认证信息已提交成功', 'success')
      
      setTimeout(() => {
        router.back()
      }, 1500)
    } else {
      throw new Error(response.error || '提交失败')
    }
  } catch (error) {
    console.error('❌ 提交失败:', error)
    showToast(error.message || '提交失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.idcard-verification-page {
  min-height: 100vh;
  background: #f5f7fa;
}

/* 顶部导航 */
.header {
  background: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  width: 40px;
  height: 40px;
}

.logo-text {
  font-size: 20px;
  font-weight: 700;
  color: #1a1a1a;
  letter-spacing: 1px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 20px;
  background: #f5f7fa;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn:hover {
  background: #ffffff;
  border-color: #00c48f;
  color: #00c48f;
}

.back-btn svg {
  width: 16px;
  height: 16px;
}

/* 主体内容 */
.main-content {
  padding: 40px 24px;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
}

/* 页面标题 */
.page-header {
  text-align: center;
  margin-bottom: 48px;
}

.title-icon {
  font-size: 64px;
  margin-bottom: 16px;
  animation: bounce 2s infinite;
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  color: #1a1a1a;
  margin-bottom: 12px;
}

.page-subtitle {
  font-size: 16px;
  color: #666;
}

/* 上传区域 */
.upload-section {
  background: #ffffff;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 32px;
}

.upload-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 32px;
  margin-bottom: 32px;
}

.upload-card {
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.required-badge {
  padding: 2px 8px;
  background: #fff1f0;
  color: #ff4d4f;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.upload-area {
  position: relative;
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
  aspect-ratio: 3 / 2;
}

.upload-area:hover {
  border-color: #00c48f;
  background: #f0fff9;
}

.upload-area.drag-over {
  border-color: #00c48f;
  background: #e6fff5;
  transform: scale(1.02);
}

.upload-area.has-image {
  border-style: solid;
  border-color: #00c48f;
  background: transparent;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 32px;
}

.upload-icon {
  width: 64px;
  height: 64px;
  color: #bbb;
  margin-bottom: 16px;
}

.upload-icon svg {
  width: 100%;
  height: 100%;
}

.upload-text {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 13px;
  color: #999;
  text-align: center;
  line-height: 1.6;
}

.image-preview {
  position: relative;
  width: 100%;
  height: 100%;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview:hover .image-overlay {
  opacity: 1;
}

.overlay-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  background: #ff4d4f;
  color: #ffffff;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.overlay-btn:hover {
  background: #ff7875;
  transform: translateY(-2px);
}

.overlay-btn svg {
  width: 16px;
  height: 16px;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 6px;
}

.file-name {
  font-size: 13px;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 12px;
  color: #999;
  margin-left: 12px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
}

.submit-btn {
  min-width: 200px;
  height: 48px;
  padding: 0 32px;
  background: linear-gradient(135deg, #00c48f 0%, #00b380 100%);
  color: #ffffff;
  border: none;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.submit-btn:hover:not(.disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 196, 143, 0.4);
}

.submit-btn.disabled {
  background: #e5e5e7;
  color: #999;
  cursor: not-allowed;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top-color: #ffffff;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 识别结果区域 */
.result-section {
  background: #ffffff;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.result-header {
  text-align: center;
  margin-bottom: 32px;
}

.result-icon {
  width: 64px;
  height: 64px;
  margin: 0 auto 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: 700;
  animation: scaleIn 0.5s ease-out;
}

.result-icon.success {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  color: #ffffff;
}

@keyframes scaleIn {
  from {
    transform: scale(0);
  }
  to {
    transform: scale(1);
  }
}

.result-title {
  font-size: 24px;
  font-weight: 700;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.result-subtitle {
  font-size: 14px;
  color: #999;
}

.result-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.info-card {
  padding: 24px;
  background: #f5f7fa;
  border-radius: 12px;
}

.info-card-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e0e0e0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-label {
  font-size: 13px;
  color: #999;
  font-weight: 500;
}

.info-value {
  font-size: 15px;
  color: #333;
  font-weight: 500;
}

.info-value.highlight {
  color: #00c48f;
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 2px;
}

.photo-preview-card {
  padding: 24px;
  background: #f5f7fa;
  border-radius: 12px;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.photo-item {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.photo-label {
  font-size: 14px;
  font-weight: 600;
  color: #666;
  text-align: center;
}

.photo-item img {
  width: 100%;
  aspect-ratio: 3 / 2;
  object-fit: cover;
  border-radius: 8px;
  border: 2px solid #e0e0e0;
}

.confirm-actions {
  display: flex;
  justify-content: center;
  padding-top: 16px;
}

.confirm-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 32px;
  background: linear-gradient(135deg, #00c48f 0%, #00b380 100%);
  color: #ffffff;
  border: none;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.confirm-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 196, 143, 0.4);
}

.confirm-btn svg {
  width: 20px;
  height: 20px;
}

/* Toast 提示 */
.toast {
  position: fixed;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 24px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  font-size: 15px;
  font-weight: 500;
}

.toast.success {
  color: #00c48f;
}

.toast.error {
  color: #ff4d4f;
}

.toast-icon {
  display: flex;
}

.toast-icon svg {
  width: 22px;
  height: 22px;
}

.toast-enter-active,
.toast-leave-active {
  transition: all 0.3s ease;
}

.toast-enter-from {
  opacity: 0;
  transform: translateX(-50%) translateY(-20px);
}

.toast-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(-20px);
}

/* 淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .upload-container {
    grid-template-columns: 1fr;
    gap: 24px;
  }

  .info-grid,
  .photo-grid {
    grid-template-columns: 1fr;
  }

  .page-title {
    font-size: 24px;
  }

  .title-icon {
    font-size: 48px;
  }

  .upload-section {
    padding: 24px;
  }

  .result-section {
    padding: 24px;
  }
}
</style>

